<?php

$groups = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}iusers_groups ORDER BY title ASC");
$currencies = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}isubscribe_currencies ORDER BY title ASC");



if(get('sub_id')!=''){
    // have selected a subscription to edit
	$subId = (int) get('sub_id');

	if($DB->countRows(cms_db_prefix().'isubscribe_subscriptions', "id = '{$subId}'")==0){
		// invalid subscription
        Antz::addError($this->Lang('invalid_subscription'));
		Antz::redir($actionUrls['edit']);
	};

    // valid subscription
    
	$subData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}isubscribe_subscriptions WHERE id = '{$subId}'");
	$prices = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}isubscribe_subscription_prices WHERE subscription_id = '{$subId}'");

	if(get('delete')==1){
		// wanting to delete the subscription
		if(Antz_IntelliForm::submitted('edit')){
			$DB->delete(cms_db_prefix().'isubscribe_subscriptions', "id = '{$subData['id']}'");
			$DB->delete(cms_db_prefix().'isubscribe_subscription_prices', "subscription_id = '{$subData['id']}'");
			Antz::addSuccess($this->Lang('subscription_deleted', $subData['keyname']));
			Antz::redir($actionUrls['edit']);
		};

		$form = Antz::newObject('Antz_Form', 'edit');
		$form->setAction(THIS_PAGE_URL);
		$block = $form->add('full');
		$fs = $block->add($this->Lang('confirm_deletion'));
		$fs->addInput('submit', 'submitBtn', '&nbsp;', $this->Lang('yes_delete'));

		echo '<h2>'.$this->Lang('confirm_deletion_of', $subData['title']).'</h2>';
		echo $form->render();
		return;

	}

	if(Antz_IntelliForm::submitted('edit')){
		$error = false;
		$keyname = preg_replace('/[^a-zA-Z0-9_\-\.]/', '', post('keyname'));
		$title = post('title');
		$grps = preg_replace('/[^a-zA-Z0-9,]/', '', post('groups'));
		$numPrices = (int) post('numPrices');
		$duration = (int) post('duration');
		$isActive = (int) post('isActive');
		if($this->CheckPermission($this->GetName().' PHP')) $code = post('code');
		else $code = '';

		// begin checks
		if($subData['keyname']!=$keyname && $DB->countRows(cms_db_prefix().'isubscribe_subscriptions', "keyname = '{$keyname}'")>0){
			$error = true;
			Antz::addFormError('keyname', $this->Lang('already_registered_sub'));
		};
		if(trim($title)==''){
			$error = true;
			Antz::addFormError('title');
		};

		$grps = explode(',', $grps);
		$noGroups = true;
		foreach($grps as $k=>$group){
			if($DB->countRows(cms_db_prefix().'iusers_groups', "keyname = '{$group}'")>0){
				$noGroups = false;
			}else{
				unset($grps[$k]);
			};
		};

		if($noGroups && trim($code)==''){
			$error = true;
			if($this->CheckPermission($this->GetName().' PHP')) $extra = $this->Lang('error_groups_extra');
			else $extra = '';
			Antz::addFormError('groups', $this->Lang('error_groups').$extra);
			if($this->CheckPermission($this->GetName().' PHP')) Antz::addFormError('code', $this->Lang('enter_code_here'));
		};

		if($this->CheckPermission($this->GetName().' PHP')){
			if(trim($code)!=''){
				if(!Antz_Filter::checkPHPCode($code)){
					$error = true;
					Antz::addFormError('code', $this->Lang('error_code'));
				};
			};
		};

		$prices = array();
		for($i=0; $i<$numPrices; $i++){
			$cur = preg_replace('/[^a-zA-Z0-9\-_]/', '', post('cur_'.$i));
			$price = (float) post('price_'.$i);
			$grp = preg_replace('/[^a-zA-Z0-9\-_]/', '', post('group_'.$i));
			if($price > 0 && $DB->countRows(cms_db_prefix().'isubscribe_currencies', "keyname = '{$cur}'")>0 && $DB->countRows(cms_db_prefix().'iusers_groups', "keyname = '{$grp}'")>0){
				$prices[] = array(
					'currency_key' => $cur,
					'price' => $price,
					'group_key' => $grp
				);
			}
		};
		if(count($prices)==0){
			$error = true;
			Antz::addError($this->Lang('error_price'));
		};
		if($duration < 0){
			$error = true;
			Antz::addFormError('duration', $this->Lang('error_duration'));
		};

		if(!$error){
			// ok to create the new subscription

			$dbParams = array(
				'keyname' => $keyname,
				'groups' => implode(',', $grps),
				'title' => $title,
				'description' => '',
				'duration' => $duration
			);

			if($this->CheckPermission($this->GetName().' PHP')) $dbParams['php_code'] = $code;
/*
			echo '<pre>';
			var_dump($dbParams);
			echo '</pre>';
//$DB->debug(true);
*/
			$DB->update(cms_db_prefix().'isubscribe_subscriptions', $dbParams, "id = '{$subId}'");
//$DB->debug(false);
			$DB->delete(cms_db_prefix().'isubscribe_subscription_prices', "subscription_id = '{$subId}'");

			foreach($prices as $k=>$v){
				$dbParams = array(
					'subscription_id' => $subId,
					'currency_key' => $v['currency_key'],
					'price' => $v['price'],
					'group_key' => $v['group_key']
				);

				$DB->insert(cms_db_prefix().'isubscribe_subscription_prices', $dbParams);

			};
//eval($code);
			Antz::addSuccess($this->Lang('sub_updated'));
			Antz::redir($actionUrls['edit']);

		};


	}





	// build the form

	$form = Antz::newObject('Antz_Form', 'edit');
	$form->setAction($Antz->addParamsToUrl($actionUrls['edit'], array('sub_id'=>$subId)));
	$form->setId('new_form');

	$block = $form->add('full');

	$fs = $block->add('Prices for new subscription');
	$fs->setId('fs1');

	// currencies dummy for javascript to clone
	$curSel = Antz::newObject('Antz_Form_Components_Select', array('cur_', $this->Lang('currency'), post('cur_')));
	foreach($currencies as $k=>$cur){
		$curSel->add($cur['title'], $cur['keyname']);
	};
	$curSel->setId('currenciesDummy');
	$fs->addLongTag('div', $curSel->render())->addParameter('style', 'display: none');

	// groups dummy for javascript to clone
	$groupSel = Antz::newObject('Antz_Form_Components_Select', array('group_', 'Group ', post('group_')));
	foreach($groups as $k=>$v){
		$groupSel->add($v['title'], $v['keyname']);
	};
	$groupSel->setId('groupsDummy');
	$fs->addLongTag('div', $groupSel->render())->addParameter('style', 'display: none');

    // link to add another price
    $addLink = '
    <a href="javascript: ISubscribe_Admin.addPrice()" class="pageoptions">
    <img src="themes/NCleanGrey/images/icons/system/newobject.gif" 
    class="systemicon" alt="'.$this->Lang('add_price').'" 
    title="'.$this->Lang('add_price').'" />'.$this->Lang('add_price').'
    </a> 
    ';
    $fs->addLongTag('p', $addLink);
    

	// re-create the currencies if the form has been submitted and returned with errors
	$numPrices = (int) count($prices);
	$fs->addInput('hidden', 'numPrices', '&nbsp;', $numPrices);
	for($i=0; $i<$numPrices; $i++){
    	$delLink = '
        <a href="javascript: ISubscribe_Admin.delPrice('.$i.')">
        <img src="themes/NCleanGrey/images/icons/system/delete.gif" alt="'.
        $this->Lang('delete_price').'" title="'.$this->Lang('delete_price').'" /></a>';

		// currency for this price
		$curSel = Antz::newObject('Antz_Form_Components_Select', array('cur_'.$i, 'Currency '.$i, post('cur_'.$i, $prices[$i]['currency_key'])));
		foreach($currencies as $k=>$cur){
			$curSel->add($cur['title'], $cur['keyname']);
		};
		$curSel->showLabel(false);
		$curSel->setWrap(false);

		// groups for upgrading
		$groupSel = Antz::newObject('Antz_Form_Components_Select', array('group_'.$i, 'Group '.$i, post('group_'.$i, $prices[$i]['group_key'])));
		foreach($groups as $k=>$v){
			$groupSel->add($v['title'], $v['keyname']);
		};
		$groupSel->showLabel(false);
		$groupSel->setWrap(false);

		// lets now assemble the price component
		$component = $fs->addInput('text', 'price_'.$i, 'Price', post('price_'.$i, $prices[$i]['price']));
		$component->addAftertext($curSel->render());
		$component->addAftertext($groupSel->render());
		$component->addAftertext($delLink);
		$component->setId('price_'.$i);
	};


	$fs = $block->add($this->Lang('sub_details'));


	$fs->addInput('text', 'keyname', 'Keyname', post('keyname', $subData['keyname']));
	$fs->addInput('text', 'title', 'Title', post('title', $subData['title']));
	$newGroupLink = '<a href="'.str_replace(array('ISubscribe', 'active_tab=new'), array('IUsers', 'active_tab=groups'), $actionUrls['new']).'">'.$this->Lang('add_group').'</a>';
	$txt = $fs->addInput('textarea', 'groups', $this->Lang('groups_to_grant'), post('groups', $subData['groups']));
	$sel = Antz::newObject('Antz_Form_Components_Select', array('group', $this->Lang('group'), '', $newGroupLink));
	$sel->add($this->Lang('add_remove_groups'), '');
	foreach($groups as $k=>$v){
		$sel->add($v['title'], $v['keyname']);
	};
	$sel->showLabel(false);
	$sel->setWrap(false);
	$sel->addJsEvent('onchange', 'ISubscribe_Admin.toggleGroup(this, \''.$txt->getId().'\')');
	$txt->addAftertext($sel->render());
	$txt->addClass('groups');

	if($this->CheckPermission($this->GetName().' PHP')) $fs->addInput('textarea', 'code', $this->Lang('code_notes'), post('code', $subData['php_code']));

	$fs->addInput('text', 'duration', 'Duration (days)', post('duration', $subData['duration']))->addAftertext($this->Lang('0_never_expires'));

	$chk = $fs->addCheckboxGroup('isActive');
	$chk->add('isActive', $this->Lang('is_active'), '1', post('isActive', $subData['is_active']));

	$fs->addInput('submit', 'submitBtn', '&nbsp;', 'Submit');


	echo $form->render();



}else{
	// have to choose a subscription to edit

	$subs = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}isubscribe_subscriptions ORDER BY is_deleted ASC, is_active DESC, title ASC");

        $allUsers = $DB->fetchAll("SELECT first_name, last_name, username, id FROM {$this->config['db_prefix']}iusers ORDER BY first_name ASC");
        

	foreach($subs as $k=>$v){
		// get some info to display about each subscription
        
        $subs[$k]['groups'] = explode(',', $v['groups']);
        
        $subs[$k]['num_subscribers'] = $DB->countRows(cms_db_prefix().'isubscribe_users_to_subscriptions', "subscription_id = '{$v['id']}'");
        
        if($v['is_active']){
            $subs[$k]['toggleActivateUrl'] = $Antz->addParamsToUrl($actionUrls['edit'], array('deactivate'=>1, 'sub_id'=>$v['id']));
            $subs[$k]['toggleActivateImg'] = 'themes/NCleanGrey/images/icons/system/true.gif';
            $subs[$k]['toggleActivateText'] = $this->Lang('deactivate');
        }else{
            $subs[$k]['toggleActivateUrl'] = $Antz->addParamsToUrl($actionUrls['edit'], array('activate'=>1, 'sub_id'=>$v['id']));
            $subs[$k]['toggleActivateImg'] = 'themes/NCleanGrey/images/icons/system/false.gif';
            $subs[$k]['toggleActivateText'] = $this->Lang('activate');
        }
        
        if($v['is_deleted']){
            $subs[$k]['toggleDeleteUrl'] = $Antz->addParamsToUrl($actionUrls['edit'], array('restore'=>1, 'sub_id'=>$v['id']));
            $subs[$k]['toggleDeleteImg'] = 'themes/NCleanGrey/images/icons/system/false.gif';
            $subs[$k]['toggleDeleteText'] = $this->Lang('restore');
        }else{
            $subs[$k]['toggleDeleteUrl'] = $Antz->addParamsToUrl($actionUrls['edit'], array('delete'=>1, 'sub_id'=>$v['id']));
            $subs[$k]['toggleDeleteImg'] = 'themes/NCleanGrey/images/icons/system/delete.gif';
            $subs[$k]['toggleDeleteText'] = $this->Lang('delete');
        }
        
        
        
        // urls to edit and delete
        $subs[$k]['editUrl'] = $Antz->addParamsToUrl($actionUrls['edit'], array('sub_id'=>$v['id']));
	$subs[$k]['deleteUrl'] = $Antz->addParamsToUrl($actionUrls['edit'], array('sub_id'=>$v['id'], 'delete'=>1));


        // ability to add a user to this subscription
        $addUserOpts = array('none' => $this->Lang('none'));
        $delUserOpts = array('none' => $this->Lang('none'));
        foreach($allUsers as $kuser=>$user){
            if($DB->countRows($this->config['db_prefix'].'isubscribe_users_to_subscriptions', "user_id = '{$user['id']}' AND subscription_id = '{$v['id']}'")==0){
                // not a subscriber
                $addUserOpts[$user['id']] = $user['first_name'].' '.$user['last_name'].' ['.$user['username'].']';
            }else{
                // already subscribed!
                $delUserOpts[$user['id']] = $user['first_name'].' '.$user['last_name'].' ['.$user['username'].']';
            }
        }

        $formFields = array(
            array(
                'type' => 'hidden',
                'name' => 'subscriptionid',
                'value' => $v['id']
            ),
            array(
                'type' => 'select',
                'name' => 'add_userid',
                'value' => post('add_userid'),
                'options' => $addUserOpts,
                'label' => $this->Lang('user_to_add')
            ),
            array(
                'type' => 'submit',
                'name' => 'addBtn',
                'value' => $this->Lang('add_user'),
                'label' => '&nbsp;'
            )

        );

        $form = Antz::makeRapidForm($formFields, $this->Lang('add_user'), 'ISubscribe_AddUser');
        $form->setAction($actionUrls['users']);
	$subs[$k]['addUser'] = $form->render();


        $formFields = array(
            array(
                'type' => 'hidden',
                'name' => 'subscriptionid',
                'value' => $v['id']
            ),
            array(
                'type' => 'select',
                'name' => 'del_userid',
                'value' => post('del_userid'),
                'options' => $delUserOpts,
                'label' => $this->Lang('user_to_delete')
            ),
            array(
                'type' => 'submit',
                'name' => 'delBtn',
                'value' => $this->Lang('delete_user'),
                'label' => '&nbsp;'
            )

        );

        $form = Antz::makeRapidForm($formFields, $this->Lang('add_user'), 'ISubscribe_AddUser');
        $form->setAction($actionUrls['users']);
	$subs[$k]['viewUsers'] = $form->render();

        

    };

	$this->smarty->assign('subs', $subs);

        if($this->CheckPermission($this->GetName().' Users')){
            $this->smarty->assign('can_manage_users', true);
        }else{
            $this->smarty->assign('can_manage_users', false);
        }

	echo $this->ProcessTemplate('admin.edit.select.tpl');

}















